package com.orm.mapper;

import com.orm.annotation.TableId;
import com.spring.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 对基础服务层的实现
 */
@Slf4j
public class BaseService<M extends BaseMapper<T>,T> implements IService<T>{
	// 利用自动注入
	@Autowired
	protected M  baseMapper;   // BaseMapper<User>
	
	// protected Class<M> mapperClass;    // 好像没什么用
	
	protected Class<T> entityClass ;      // 好像没什么用
	
	
	private Field keyField;  // 主键字段
	
	public BaseService() {
		Type genericSuperclass = this.getClass().getGenericSuperclass();
		if (genericSuperclass instanceof ParameterizedType) {
			
			this.entityClass = (Class<T>) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[1];
			
			Field[] fields = entityClass.getDeclaredFields();
			String keyName = null;
			for (Field field : fields) {
				if (field.isAnnotationPresent(TableId.class)) {
					keyField = field;
					break;
				}
			}
			if (keyField == null) {
				// 没有查到 @TableId 字段
				for (Field field : fields) {
					if (field.getName().equals("id")) {
						keyField = field;
						break;
					}
				}
			}
		}
	}
	
	
	@Override
	public BaseMapper<T> getBaseMapper() {
		return this.baseMapper;
	}
	
	@Override
	public Class<T> getEntityClass() {
		return this.entityClass;
	}
	
	@Override
	public boolean saveOrUpdate(T entity) {
		if(keyField == null){
			log.error("实体类中不知道哪个是主键字段");
			throw new RuntimeException("无法确认调用insert还是update");
		}
		try {
			keyField.setAccessible(true);
			Object o = keyField.get(entity);
			if(o == null){
				// 调用 insert
				return this.save(entity);
			}else{
				// 调用 update
				return this.update(entity);
			}
		} catch (IllegalAccessException e) {
			throw new RuntimeException("访问错误");
		}
	}
}
